<template>
    <div class="container">
        <!--班级管理标题设置-->
        <a-layout class="classes_container">
            <a-layout-header class="classes_header">
                <span>班级管理</span>
            </a-layout-header>
            <!--班级管理页面内容设置-->
            <a-layout-content class="classes_content">
                <div>
<!--                  删除搜索栏-->
<!--                    <ARow class="row1" :gutter="4">-->
<!--                        <ACol span="1" class="itemIndex" >年级：</ACol>-->
<!--                        <ACol span="3" style="margin-right: 0.5em;">-->
<!--                            &lt;!&ndash;选择器中的年级信息&ndash;&gt;-->
<!--                            <a-select show-search placeholder="" v-model="classRecord.grade"  default-value="" style="width: 100%" @change="getGrade">-->
<!--                                <a-select-option :value="gradeData[index]" v-for="(item,index) in gradeData" :key="item">-->
<!--                                    {{item}}-->
<!--                                </a-select-option>-->
<!--                            </a-select>-->
<!--                        </ACol>-->
<!--                        <ACol span="1" class="itemIndex" >专业：</ACol>-->
<!--                        <ACol span="4" style="margin-right: 0.5em;">-->
<!--                            &lt;!&ndash;选择器中的专业信息&ndash;&gt;-->
<!--                            <a-select show-search placeholder="" v-model="classRecord.major"  default-value="" style="width: 100%" @change="getMajor" :disabled="showMajordata"     >-->
<!--                                <a-select-option :value="majorData[index]" v-for="(item,index) in majorData" :key="item">-->
<!--                                    {{item}}-->
<!--                                </a-select-option>-->
<!--                            </a-select>-->
<!--                        </ACol>-->
<!--                        <ACol span="1" class="itemIndex" >班号：</ACol>-->
<!--                        <ACol span="3">-->
<!--                            &lt;!&ndash;选择器中的班号信息&ndash;&gt;-->
<!--                            <a-select show-search placeholder="" v-model="classRecord.number" default-value="" style="width: 7em" @change="searchClasses" :disabled="showNumberdata">-->
<!--                                <a-select-option :value="numberData[index]" v-for="(item,index) in numberData" :key="item">-->
<!--                                    {{item}}-->
<!--                                </a-select-option>-->
<!--                            </a-select>-->
<!--                        </ACol>-->
<!--                        <ACol span="3"><AButton type="primary" size="default" style="width:80%;" @click="searchClasses">查询</AButton></ACol>-->
<!--                        <ACol span="3"><AButton type="default" size="default" style="width:80%;" @click="onReset">重置</AButton></ACol>-->
<!--                    </ARow>-->
                    <ARow class="row2" >
                        <ACol span="3"><a-Button type="primary" size="default" style="width:80%" @click="addClasses('')">添加</a-Button></ACol>
                        <ACol span="3"><AButton type="danger" size="default"  style="width:80%" @click="showDeleteClassesModel">批量删除</AButton></ACol>
                    </ARow>
                </div>
                <!--表格设置，样式设置“class，size，bordered”，数据源DataSource，表头columns,rowKey一条记录中的classesID-->
                <a-table ref="tab" class="classes_table"
                         size="small"
                         bordered
                         :data-source="dataSource"
                         :columns="columns"
                         :row-selection="{onChange:change}"
                         :pagination="false"
                         :scroll="PageSize===10||dataSource.length<=10? {}:{ y: 380 }"
                         :rowKey='record=>record.indexId'>
                    <!--操作一列中的删除设置，operation在columns中存储-->
                    <template slot="operation" slot-scope="text, record">
                        <!--表格删除的弹出确认框-->
                        <a-popconfirm
                                v-if="dataSource.length"
                                title="确认删除吗?"
                                @confirm="() => deleteClasses(record.grade,record.maj_id)"
                        >
                            <a href="#">删除</a>
                        </a-popconfirm>
                    </template>
                </a-table>
            </a-layout-content>
            <!--设置表格的页面跳转-->
            <a-layout-footer class="classes_footer">
                <a-pagination
                        class="pagination"
                        show-size-changer
                        show-quick-jumper
                        :defaultPageSize="PageSize"
                        :current="currentPage"
                        :total="count"
                        :show-total="total => `共 ${total} 条`"
                        :pageSizeOptions="pageSizeOptions"
                        @change="pageChange"
                        @showSizeChange="showSizeChange"
                />
            </a-layout-footer>
        </a-layout>
        <addClasses ref="addcs" @get="pageChange(1,PageSize)" @gett="getClasses"></addClasses>
        <!--批量删除确认Model-->
        <!--触发批量删除课程-->
        <ClassesBatchDeleteModel ref="deletecs" @del="batchDeleteClasses"></ClassesBatchDeleteModel>
    </div>
</template>

<script>
    import { mapState } from 'vuex'
    import addClasses from "./addClasses";
    import ClassesBatchDeleteModel from "./ClassesBatchDeleteModel";
    const rowSelection = {
        onChange: 'change',
    };
    export default {
        name: "classesManage",
        components: {ClassesBatchDeleteModel, addClasses},
        data() {
            return {
                flag:0,//标志位，第一次查询时使页面为第一页
                group:0,//标志下拉框的内容是否清空，默认不清空
                searchValue:'',
                selectedRowKeys:[],//默认选中第几行
                count: 0,//总页数
                currentPage:1,//当前页
                PageSize:10,
                pageSizeOptions:['10','20','30'],//页面可以显示的条数
                rowSelection,
                //多选（前面复选框的内容）
                dataSource: [],
                gradeData: [],
                majorData: [],
                numberData: [],
                columns: [
                    {
                        title: '年级',
                        key:'grade',
                        dataIndex: 'grade',
                        width: '15%',
                        align: 'center',
                        sorter: (a, b) =>{
                            if(a.grade.localeCompare(b.grade)==0){
                                if(a.major.localeCompare(b.major)==0){
                                    return a.number-b.number;
                                }else{
                                    return a.major.localeCompare(b.major);
                                }
                            } else{
                                return a.grade.localeCompare(b.grade);
                            }
                        }
                    },
                    {
                        title: '专业',
                        key:'major',
                        dataIndex: 'major',
                        align: 'center',
                        width: '40%',
                        sorter: (a, b) => {
                            if(a.major.localeCompare(b.major)==0){
                                if(a.grade.localeCompare(b.grade)==0){
                                    return a.number-b.number;
                                }else{
                                    return a.grade.localeCompare(b.grade);
                                }
                            }else{
                                return a.major.localeCompare(b.major);
                            }
                        },
                    },
                    {
                        title: '班号',
                        key:'number',
                        dataIndex: 'number',
                        align: 'center',
                        width: '15%',
                    },
                    {
                        title: '操作',
                        key:'operation',
                        align: 'center',
                        scopedSlots: {customRender: 'operation'},
                    },
                ],//每一列的设置
                //动态绑定选择器中的值
                classRecord: {
                    classesId:'',
                    grade: '',
                    major:'',
                    number:''
                },
                showMajordata:true,  //默认命令选择框是禁用的
                showNumberdata:true, //默认命令选择框是禁用的
            }
        },
        methods: {
            getGrade(){ // 根据年级获取专业
                const info={
                    // majorValue: this.classRecord.major,
                    collegeId:this.accessState.collegeId, //获取管理员ID（需要改动）
                    grade: this.classRecord.grade,
                };
                //console.log("改变了年级")
                // 如果第一个选择框有值，那么第二个选择框可选，否则禁用
                if(this.classRecord.grade.length > 0){
                    this.showMajordata = false;
                }else{
                    this.showMajordata = true;
                }
                this.majorData=[];
                this.$store.dispatch('classes/getMajors',info)
                    .then(res => {
                        this.majorData.push(...res.data.majors)
                    })
                    .catch(err => {
                        this.$message.error(err.msg)
                    })
            },
            getMajor(){
                const info={
                    //numberValue:this.classRecord.number,
                    grade: this.classRecord.grade,
                    major: this.classRecord.major,
                };
                // 如果第一个选择框有值，那么第二个选择框可选，否则禁用
                if(this.classRecord.major.length>0){
                    this.showNumberdata = false;
                }else{
                    this.showNumberdata = true;
                }
                this.numberData=[];
                this.$store.dispatch('classes/getNumbers',info)
                    .then(res => {
                        this.numberData.push(...res.data.numbers)
                    })
                    .catch(err => {
                        this.$message.error(err.msg)
                    })
            },
            //获取多选框的值
            change(selectedRowKeys, selectedRows){
                this.selectedRowKeys=selectedRowKeys;
                this.selectedRowKeys=[];
                selectedRows.some(item=>{this.selectedRowKeys.push({grade:item.grade,majId:item.maj_id})});
            },
            //页数变化
            pageChange(page, pageSize){
                this.currentPage=page;
                this.PageSize=pageSize;
                if(this.searchValue === ''){ //如果搜索框中的数据为空，调用getClasses()，返回所有班级列表
                    this.getClasses();
                }else{
                    this.search(this.searchValue)
                }
            },
            //每页显示数量变化
            showSizeChange(current, size){
                this.currentPage=1;
                this.PageSize=size;
                if(this.searchValue === ''){ //如果搜索框中的数据为空，调用getClasses()，返回所有班级列表
                    this.getClasses();
                }else{
                    this.search(this.searchValue)
                }
            },
            //获取班级列表信息
            getClasses(){
                const info = {
                    collegeId: this.accessState.collegeId, //获取管理员ID（需要改动）
                    currentPage: this.currentPage,               //获取当前页
                    rows: this.PageSize,                         //每页的总行数
                    token: this.accessState.token,
                };
                this.$store.dispatch('classes/getClasses',info).then(data=>{                  //调用api中的classes的getClasses()
                    if(data.code === 1){
                        this.dataSource = data.data.classRecords;         //获取数据，存储到dataSource
                        this.count = parseInt(data.data.count);             //获取总数
                    }else{
                        this.$message.error(data.msg);          //返回错误信息
                    }
                }).catch(err => {
                    this.$message.error(err.msg);
                })
            },
            searchClasses() {
                if(this.classRecord.grade === ''&&this.classRecord.major === ''&&this.classRecord.number === ''){   //判断选择器中的内容如果全为空显示所有班级列表
                    this.currentPage=1;
                    this.getClasses();
                    this.flag=0;
                } else{
                    if(this.flag === 0) {
                        this.currentPage=1
                    } //第一次查询时，要到第一页
                    this.flag++;
                    const info = {
                        classRecord: this.classRecord,                     //选择器中的班级记录
                        collegeId: this.accessState.collegeId,        //学院Id
                        currentPage: this.currentPage,                      //当前页数
                        rows: this.PageSize,                                //当前行数
                        token: this.accessState.token,
                    };
                    this.$store.dispatch("classes/queryClasses",info).then(data=>{                       //info作为参数传递，返回查找到的数据列表
                            this.dataSource = data.data.classRecords;             //查找到的符合要求的数据存储到dataSource
                            this.count = data.data.count;                   //获取data的总数
                    }).catch(err => {
                        this.$message.error(err.msg);
                    })
                }
            },
            //重置按钮事件
            onReset() {
                this.classRecord.grade = '';
                this.classRecord.major = '';
                this.classRecord.number = '';
                this.showMajordata=true;
                this.showNumberdata=true;
                this.getClasses()
            },
            //删除指定课程，key为获取所在行
            deleteClasses(grade,majId) {
                //调用api，classes中的delete接口
                this.$store.dispatch("classes/deleteClasses",{grade: grade,majId: majId, token: this.accessState.token})
                    .then(data => {
                            this.$message.success(data.msg);
                            //调用方法pageChange，传入当前页和当前行数
                            this.pageChange(this.currentPage, this.PageSize);
                        })
                    .catch(err=>{
                        this.$message.error(err.msg);
                })
            },
            //显示删除班级弹窗
            showDeleteClassesModel(){
                if(this.selectedRowKeys.length === 0){
                    this.$message.info('所选内容不能为空');
                }else{
                    this.$refs.deletecs.showModel();
                }
            },
            //批量删除课程
            batchDeleteClasses(){
                if(this.selectedRowKeys.length === 0){
                    this.$message.info('所选内容不能为空');
                }else{
                  console.log(this.selectedRowKeys)
                    this.$store.dispatch('classes/batchDeleteClasses',{'records': this.selectedRowKeys,token:this.accessState.token}).then(data=>{
                        //调用api中的batchDeleteClasses，传入所选行数为classesIds
                        this.$message.success(data.msg);
                        this.pageChange(this.currentPage, this.PageSize);
                        this.selectedRowKeys = []
                    }).catch(err=>{
                        this.$message.error(err.msg);
                    })
                }
            },
            //新建课程
            addClasses(judge){
                this.$refs.addcs.showModel(judge);
            }
        },
        //初始化时，获取所有课程列表
        created() {
            this.getClasses();
            this.$store.dispatch('classes/getGrades')
                .then((res) => {
                    this.gradeData.push(...res.data.grades)
                })
                .catch((err) => {
                    this.$message.error(err.msg)
                })
        },
        computed: {
            ...mapState({ // 这个是提取store中access文件夹目录下的数据
                'accessState': 'access'
            })
        }
    }
</script>

<style scoped>
    .itemIndex{
        line-height: 2em;
    }
    .container{
        width: 100%;
        height: 100%;
    }
    .classes_container{
        width: 100%;
        background-color: #fff;
    }
    .classes_header{
        height: 2.8em;
        text-align: left;
        font-size: 1.4em;
        font-weight: bolder;
        background-color: #fff;
        padding: 0em 1.5em 0em 1.5em;
    }
    .classes_content{
        text-align: left;
        padding: 0em 2em;
        overflow: hidden;
    }
    a{
        margin: 1em ;
    }
    .classes_footer{
        background-color: #fff;
    }
    .row1 {
        margin-top: 1%;
    }
    .row2 {
        margin-top: 1%;
        margin-left: 0.1%;
        margin-bottom: 2%;
    }
</style>
<style>
    .classes_table th{
        background-color: #cccccc !important;
        font-size: 1em !important;
        font-weight: bold !important;
    }
</style>
